package com.bjpowernode.springboot.controller;

import com.bjpowernode.springboot.entity.Student;
import com.bjpowernode.springboot.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/student-redis")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/save-redis")
    @ResponseBody
    public String saveStudent(Integer id, String name, Integer age) {
        Student student = new Student();
        packStudent(student,id,name,age);
        int opt = studentService.saveStudent(student);
        if (opt > 0) {
            return "成功保存到redis缓存中";
        }
        return "保存失败";
    }

    /**
     * 通过学生编号查询从缓存中查询学生信息
     * 1. 先从redis缓存中获取
     * 2. 如果redis缓存中有直接返回信息到页面中即可
     * 3. 如果redis缓存中没有，我们从mysql数据库中获取当前的学生信息
     * 然后将其放置到缓存中，
     * 4. 返回学生的信息到页面中
     * @param id
     * @return
     */
    @RequestMapping("/get-redis")
    @ResponseBody
    public Object getStudent(Integer id) {
        Student student = studentService.getStudent(id);
        if (student == null) {
            return "编号为：" + id + "的学生不存在";
        }
        return student;
    }

    /**
     * 测试Redis的心跳机制
     * @return
     */
    @RequestMapping("/ping")
    @ResponseBody
    public String ping() {
        return studentService.ping();
    }


    public void packStudent(Student student, Integer id, String name, Integer age) {
        student.setId(id);
        student.setName(name);
        student.setAge(age);
    }

}
